package com.chushouya.controller.open;


import com.chushouya.common.annotations.AuthSkip;
import com.chushouya.common.constant.ServiceType;
import com.chushouya.order.constants.AlipaySpiResultCodeEnum;
import com.chushouya.order.service.admin.AlipaySpiCommerceService;
import com.general.framework.core.lang.Jsons;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.util.HashMap;
import java.util.Map;

import static com.chushouya.common.util.OrderUtil.requestToMap;

/**
 * 支付宝网关
 */
@RestController
@RequestMapping(ServiceType.OPEN_API + "/alipaySpiCommerce")
@Slf4j

public class AlipaySpiCommerceController {

    @Resource
    private AlipaySpiCommerceService alipaySpiCommerceService;

    /**
     * 支付宝网关 https://test-api.suhuishou.com/suhuishou-order/open-api/alipaySpiCommerce/callback
     */
    @PostMapping("/callback")
    @AuthSkip
    public Object alipaySpiCommerceCallBack(HttpServletRequest request) {
//        try {
        Object data = alipaySpiCommerceService.alipaySpiCommerceCallBack(requestToMap(request));
        log.info("支付宝网关回调结果:{}", Jsons.toJSONString(data));
            return buildResponse(data);
//        } catch (Exception e) {
//            log.error("支付宝网关回调异常:{}", e.getMessage());
//            Object object3 = buildFailResponse(e.getMessage());
//            log.info("object3:{}", Jsons.toJsonString(object3));
//            return object3;
//        }
    }

    private Map<String, Object> buildResponse(Object data) {
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> response = new HashMap<>();
        response.put("code", AlipaySpiResultCodeEnum.SUCCESS.value());
        response.put("msg", AlipaySpiResultCodeEnum.SUCCESS.named());
        response.put("data", data);
        result.put("response", response);
        result.put("sign", "");
        return result;
    }

    private Map<String, Object> buildFailResponse(String msg) {
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> response = new HashMap<>();
        response.put("msg", AlipaySpiResultCodeEnum.FAIL.named());
        response.put("code", AlipaySpiResultCodeEnum.FAIL.value());
        response.put("sub_code", "INVALID_PARAMS");
        response.put("sub_msg", msg);
        result.put("response", response);
        result.put("sign", "");
        return result;
    }
}
